package com.jason.bookworm.service.impl;

import com.jason.bookworm.dao.pojo.Book;
import com.jason.bookworm.dao.pojo.Comment;
import com.jason.bookworm.response.Result;
import com.jason.bookworm.response.StatusEnum;
import com.jason.bookworm.service.BookWareService;
import com.jason.bookworm.service.CommentService;
import com.jason.bookworm.service.HandleCommentService;
import com.jason.bookworm.utils.LoginUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class HandleCommentServiceImpl implements HandleCommentService {

    @Autowired
    private CommentService commentService;

    @Autowired
    private BookWareService bookWareService;

    /**
     * @param bookID 书籍id
     * @return 获取所有评论
     */
    @Override
    public Result<List<Comment>> getAllComment(Integer bookID) {
        Book book = new Book();
        book.setId(bookID);
        List<Comment> comments = commentService.getAllCommOfBook(book);
        if (comments.isEmpty()) {
            return new Result<>(StatusEnum.GET_ERR);
        }
        return new Result<>(StatusEnum.GET_OK, comments);
    }

    /**
     * @param comment 评论
     * @return 发表状态
     */
    @Override
    public Result<Object> addOneComment(Comment comment) {
        String commentValue = comment.getComment();
        Integer bookId = comment.getBookId();
        //如果评论或书籍id为空
        if (bookId == null) {
            return Result.getResult(StatusEnum.POST_ERR, "书籍id为空！");
        }
        if (commentValue == null) {
            return Result.getResult(StatusEnum.POST_ERR, "评论为空！");
        }
        //如果书籍不存在
        if (bookWareService.getBookById(comment.getBookId()) == null) {
            return Result.getResult(StatusEnum.POST_ERR, "书籍不存在！");
        }
        Comment comment1 = new Comment();
        //设置属性
        String username = LoginUserUtil.getCurrentUsername();
        comment1.setUsername(username);
        comment1.setBookId(bookId);
        comment1.setComment(commentValue);
        if (commentService.save(comment1)) {
            return Result.getResult(StatusEnum.POST_OK);
        }
        return Result.getResult(StatusEnum.POST_ERR);
    }

    /**
     * @param commentID
     * @return
     */
    @Override
    public Result<Object> deleteOneComment(Integer commentID) {
        //根据评论id查找评论
        Comment comment = commentService.getById(commentID);
        String username = LoginUserUtil.getCurrentUsername();
        if (comment.getUsername().equals(username)) {
            commentService.removeById(commentID);
            return Result.getResult(StatusEnum.DELETE_OK);
        }
        return Result.getResult(StatusEnum.DELETE_ERR);
    }
}
